import 'package:http/http.dart' as http;
import '../model/order.dart';
import '../model/user.dart';
import '../model/post.dart';
import '../model/comment.dart';
import '../model/album.dart';
import '../model/photo.dart';
import '../model/todo.dart';
import '../model/api_response.dart';
import '../util/http_client.dart';
import '../util/parser_utils.dart';

class JsonPlaceholderApi {
  // 用户相关接口
  static Future<ApiResponse<List<User>>> getUsers() async {
    try {
      final response = await HttpClient.get("/users");
      return ParserUtils.parseListResponse<User>(
        response,
        itemParser: (json) => User.fromJson(json),
      );
    } catch (e) {
      return ApiResponse(
        data: null,
        status: 500,
        message: "Failed to get users: $e",
      );
    }
  }

  static Future<ApiResponse<User>> getUser(int id) async {
    try {
      final response = await HttpClient.get("/users/$id");
      return ParserUtils.parseObjectResponse<User>(
        response,
        parser: (json) => User.fromJson(json),
      );
    } catch (e) {
      return ApiResponse(
        data: null,
        status: 500,
        message: "Failed to get user: $e",
      );
    }
  }

  // 帖子相关接口
  static Future<ApiResponse<List<Post>>> getPosts() async {
    try {
      final response = await HttpClient.get("/posts");
      return ParserUtils.parseListResponse<Post>(
        response,
        itemParser: (json) => Post.fromJson(json),
      );
    } catch (e) {
      return ApiResponse(
        data: null,
        status: 500,
        message: "Failed to get posts: $e",
      );
    }
  }

  static Future<ApiResponse<Post>> getPost(int id) async {
    try {
      final response = await HttpClient.get("/posts/$id");
      return ParserUtils.parseObjectResponse<Post>(
        response,
        parser: (json) => Post.fromJson(json),
      );
    } catch (e) {
      return ApiResponse(
        data: null,
        status: 500,
        message: "Failed to get post: $e",
      );
    }
  }

  // 评论相关接口
  static Future<ApiResponse<List<Comment>>> getCommentsForPost(
      int postId) async {
    try {
      final response = await HttpClient.get("/posts/$postId/comments");
      return ParserUtils.parseListResponse<Comment>(
        response,
        itemParser: (json) => Comment.fromJson(json),
      );
    } catch (e) {
      return ApiResponse(
        data: null,
        status: 500,
        message: "Failed to get comments: $e",
      );
    }
  }

  // 相册相关接口
  static Future<ApiResponse<List<Album>>> getAlbumsForUser(int userId) async {
    try {
      final response = await HttpClient.get("/users/$userId/albums");
      return ParserUtils.parseListResponse<Album>(
        response,
        itemParser: (json) => Album.fromJson(json),
      );
    } catch (e) {
      return ApiResponse(
        data: null,
        status: 500,
        message: "Failed to get albums: $e",
      );
    }
  }

  // 照片相关接口
  static Future<ApiResponse<List<Photo>>> getPhotosForAlbum(int albumId) async {
    try {
      final response = await HttpClient.get("/albums/$albumId/photos");
      return ParserUtils.parseListResponse<Photo>(
        response,
        itemParser: (json) => Photo.fromJson(json),
      );
    } catch (e) {
      return ApiResponse(
        data: null,
        status: 500,
        message: "Failed to get photos: $e",
      );
    }
  }

  // 待办事项相关接口
  static Future<ApiResponse<List<Todo>>> getTodosForUser(int userId) async {
    try {
      final response = await HttpClient.get("/users/$userId/todos");
      return ParserUtils.parseListResponse<Todo>(
        response,
        itemParser: (json) => Todo.fromJson(json),
      );
    } catch (e) {
      return ApiResponse(
        data: null,
        status: 500,
        message: "Failed to get todos: $e",
      );
    }
  }

  // 创建资源接口
  static Future<ApiResponse<Post>> createPost(Post post) async {
    try {
      final response = await HttpClient.post(
        "/posts",
        body: post.toJson(),
      );

      return ParserUtils.parseObjectResponse<Post>(
        response,
        parser: (json) => Post.fromJson(json),
      );
    } catch (e) {
      return ApiResponse(
        data: null,
        status: 500,
        message: "Failed to create post: $e",
      );
    }
  }

  // 获取用户订单
  static Future<ApiResponse<List<Order>>> getUserOrders(String userId) async {
    try {
      // JSONPlaceholder 没有订单API，这里模拟响应
      final response = await HttpClient.get("/users/$userId");


      if (response.statusCode == 200) {
        // 模拟订单数据
        final orders = [
          Order(
            id: "1001",
            userId: userId,
            items: [
              OrderItem(
                id: "101",
                name: "Product A",
                price: 19.99,
                quantity: 2,
              ),
              OrderItem(
                id: "102",
                name: "Product B",
                price: 29.99,
                quantity: 1,
              ),
            ],
            total: 69.97,
            status: "delivered",
            createdAt: DateTime(2023, 5, 15),
            updatedAt: DateTime(2023, 5, 16),
          ),
          Order(
            id: "1002",
            userId: userId,
            items: [
              OrderItem(
                id: "103",
                name: "Product C",
                price: 14.99,
                quantity: 3,
              ),
            ],
            total: 44.97,
            status: "shipped",
            createdAt: DateTime(2023, 6, 10),
            updatedAt: DateTime(2023, 6, 11),
          ),
        ];

        return ApiResponse<List<Order>>(
          data: orders,
          status: response.statusCode,
          message: "Success",
        );
      } else {
        return ApiResponse<List<Order>>(
          data: null,
          status: response.statusCode,
          message: "Failed to get user data",
        );
      }
    } catch (e) {
      if (e.toString().contains("404")) {
        // 模拟订单数据
        final orders = [
          Order(
            id: "1001",
            userId: userId,
            items: [
              OrderItem(
                id: "101",
                name: "Product A",
                price: 19.99,
                quantity: 2,
              ),
              OrderItem(
                id: "102",
                name: "Product B",
                price: 29.99,
                quantity: 1,
              ),
            ],
            total: 69.97,
            status: "delivered",
            createdAt: DateTime(2023, 5, 15),
            updatedAt: DateTime(2023, 5, 16),
          ),
          Order(
            id: "1002",
            userId: userId,
            items: [
              OrderItem(
                id: "103",
                name: "Product C",
                price: 14.99,
                quantity: 3,
              ),
            ],
            total: 44.97,
            status: "shipped",
            createdAt: DateTime(2023, 6, 10),
            updatedAt: DateTime(2023, 6, 11),
          ),
        ];

        return ApiResponse<List<Order>>(
          data: orders,
          status: 200,
          message: "Success",
        );
      }

      else {
        print("order 加载失败: ${e}");
        return ApiResponse<List<Order>>(
          data: null,
          status: 500,
          message: "Failed to get orders: $e",
        );
      }
    }}

    // 创建订单
    static Future<ApiResponse<Order>> createOrder(Order order) async {
      try {
        // 模拟创建订单
        final newOrder = Order(
          id: "100${DateTime
              .now()
              .millisecondsSinceEpoch % 1000}",
          userId: order.userId,
          items: order.items,
          total: order.total,
          status: "pending",
          createdAt: DateTime.now(),
          updatedAt: DateTime.now(),
        );

        return ApiResponse<Order>(
          data: newOrder,
          status: 201,
          message: "Order created",
        );
      } catch (e) {
        return ApiResponse<Order>(
          data: null,
          status: 500,
          message: "Failed to create order: $e",
        );
      }
    }

    // 更新订单状态
    static Future<ApiResponse<Order>> updateOrderStatus(
    String orderId,
    String newStatus
    ) async {
      try {
        // 模拟更新订单
        final order = Order(
          id: orderId,
          userId: "1",
          items: [
            OrderItem(
              id: "101",
              name: "Product A",
              price: 19.99,
              quantity: 2,
            ),
          ],
          total: 39.98,
          status: newStatus,
          createdAt: DateTime(2023, 5, 15),
          updatedAt: DateTime.now(),
        );

        return ApiResponse<Order>(
          data: order,
          status: 200,
          message: "Order status updated",
        );
      } catch (e) {
        return ApiResponse<Order>(
          data: null,
          status: 500,
          message: "Failed to update order: $e",
        );
      }
    }
  }